package com.gitee.huxing.course.conc.conc02.lock;

import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Description:
 * @ProjectName: JavaCourse
 * @Package: com.gitee.huxing.course.conc.conc02.lock
 * @ClassName: TestFair
 * @Author: huxing
 * @DateTime: 2021-08-25 下午12:09
 */
public class TestFair {

    public static volatile int race = 0;

    public static ReentrantLock lock = new ReentrantLock(true);

    public static void increase(){
        lock.lock();
        try {
            // 变量自增处理
            race++;
        } finally {
            lock.unlock();
        }
    }

    /** 最大线程数 **/
    private static final int THEADS_COUNT = 20;

    public static void main(String[] args) {
        int count = Thread.activeCount();
        long now = System.currentTimeMillis();
        System.out.println(count);
        AtomicReference<Thread> sign = new AtomicReference<>();
        Thread[] threads = new Thread[THEADS_COUNT];
        for (int i = 0; i < THEADS_COUNT; i++) {
            threads[i] = new Thread(()->{
                for (int j = 0; j < 100000; j++) {
                    increase();
                }
            });
            threads[i].start();
        }
        while (Thread.activeCount() > count){
            Thread.yield();
        }
        System.out.println(lock.getClass().getName() + " ts = " + (System.currentTimeMillis() - now));
    }
}
